#!/usr/bin/env/python
# import sip
# sip.setapi('QVariant', 2)

from PySide.QtCore import *
from PySide.QtGui import *

import datahandler
import commonfunctions

class CreateContentTab(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        self.data = datahandler.DataHandler()
        self.common = commonfunctions.CommonFunctions()
        self.parent = parent

        self.cutAction = QAction(QIcon(QDir.currentPath() + "/images/edit-cut.png"), "Cut", self)
        self.copyAction = QAction(QIcon(QDir.currentPath() + "/images/edit-copy.png"), "Copy", self)
        self.pasteAction = QAction(QIcon(QDir.currentPath() + "/images/edit-paste.png"), "Paste", self)
        self.undoAction = QAction(QIcon(QDir.currentPath() + "/images/edit-undo.png"), "Undo", self)
        self.redoAction = QAction(QIcon(QDir.currentPath() + "/images/edit-redo.png"), "Redo", self)
        self.boldAction = QAction(QIcon(QDir.currentPath() + "/images/format-text-bold.png"), "Bold", self)
        self.italicAction = QAction(QIcon(QDir.currentPath() + "/images/format-text-italic.png"), "Italic", self)
        self.underlineAction = QAction(QIcon(QDir.currentPath() + "/images/format-text-underline.png"), "Underline", self)
        self.superscriptAction = QAction(QIcon(QDir.currentPath() + "/images/superscript.png"), "Superscript", self)
        self.subscriptAction = QAction(QIcon(QDir.currentPath() + "/images/subscript.png"), "Subscript", self)
        self.justifyleftAction = QAction(QIcon(QDir.currentPath() + "/images/format-justify-left.png"), "Justify Left", self)
        self.justifycenterAction = QAction(QIcon(QDir.currentPath() + "/images/format-justify-center.png"), "Justify Center", self)
        self.justifyrightAction = QAction(QIcon(QDir.currentPath() + "/images/format-justify-right.png"), "Justify Right", self)
        self.justifyfillAction = QAction(QIcon(QDir.currentPath() + "/images/format-justify-fill.png"), "Justify Fill", self)
        self.unorderlistAction = QAction(QIcon(QDir.currentPath() + "/images/bulletlist.png"), "Unordered List", self)
        self.addnoteAction = QAction(QIcon(QDir.currentPath() + "/images/list-add.png"), "Add Note", self)
        self.delnoteAction = QAction(QIcon(QDir.currentPath() + "/images/list-remove.png"), "Delete Note", self)
        self.updatenoteAction = QAction(QIcon(QDir.currentPath() + "/images/document-save.png"), "Update Note", self)
        self.textToolbar = QToolBar()
        self.textToolbar.addAction(self.cutAction)
        self.textToolbar.addAction(self.copyAction)
        self.textToolbar.addAction(self.pasteAction)
        self.textToolbar.addAction(self.undoAction)
        self.textToolbar.addAction(self.redoAction)
        self.textToolbar.addSeparator()
        self.textToolbar.addAction(self.boldAction)
        self.textToolbar.addAction(self.italicAction)
        self.textToolbar.addAction(self.underlineAction)
        self.textToolbar.addSeparator()
        self.textToolbar.addAction(self.justifyleftAction)
        self.textToolbar.addAction(self.justifycenterAction)
        self.textToolbar.addAction(self.justifyrightAction)
        self.textToolbar.addAction(self.justifyfillAction)
        self.textToolbar.addSeparator()
        self.textToolbar.addAction(self.unorderlistAction)
        self.textToolbar.addSeparator()
        self.textToolbar.addAction(self.addnoteAction)
        self.textToolbar.addAction(self.delnoteAction)
        self.textToolbar.addAction(self.updatenoteAction)
        self.textToolbar.setStyleSheet("QToolBar { border: 0px }")
        self.boldAction.setCheckable(True)
        self.italicAction.setCheckable(True)
        self.underlineAction.setCheckable(True)
        self.justifyleftAction.setCheckable(True)
        self.justifyleftAction.setChecked(True)
        self.justifycenterAction.setCheckable(True)
        self.justifyrightAction.setCheckable(True)
        self.justifyfillAction.setCheckable(True)
        self.unorderlistAction.setCheckable(True)
        # connect actions
        self.cutAction.triggered.connect(self.cutText)
        self.pasteAction.triggered.connect(self.pasteText)
        self.boldAction.triggered[bool].connect(self.boldText)
        self.italicAction.triggered[bool].connect(self.italicText)
        self.underlineAction.triggered[bool].connect(self.underlineText)
        self.justifyleftAction.triggered[bool].connect(self.justifyText)
        self.justifycenterAction.triggered[bool].connect(self.justifyText)
        self.justifyrightAction.triggered[bool].connect(self.justifyText)
        self.justifyfillAction.triggered[bool].connect(self.justifyText)
        self.unorderlistAction.triggered[bool].connect(self.unorderlistText)

        self.addnoteAction.triggered.connect(self.addNote)
        self.delnoteAction.triggered.connect(self.delNote)
        self.updatenoteAction.triggered.connect(self.updateNote)
        self.noteList = QListWidget()
        self.noteEditor = QTextEdit()
        self.noteList.setAlternatingRowColors(True)
        self.noteList.setFrameStyle(QFrame.Panel)
        self.noteEditor.setFrameStyle(QFrame.Panel)
        self.noteList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.noteEditor.cursorPositionChanged.connect(self.updateButtons)
        self.noteList.itemSelectionChanged.connect(self.showContent)
        self.mainLayout = QVBoxLayout()
        self.listLayout = QHBoxLayout()
        self.listLayout.addWidget(self.noteList)
        self.mainLayout.addWidget(self.textToolbar)
        self.mainLayout.addWidget(self.noteEditor)
        self.mainLayout.addWidget(self.noteList)
        self.setLayout(self.mainLayout)
    
    def cutText(self):
        self.noteEditor.cut()
    def copyText(self):
        self.noteEditor.copy()
    def pasteText(self):
        self.noteEditor.paste()
    def redoText(self):
        self.noteEditor.redo()
    def undoText(self):
        self.noteEditor.undo()
    def boldText(self):
        if self.noteEditor.fontWeight() == QFont.Bold:
            self.noteEditor.setFontWeight(QFont.Normal)
            self.boldAction.setChecked(False)
        else:
            self.noteEditor.setFontWeight(QFont.Bold)
            self.boldAction.setChecked(True)
    def italicText(self):
        if self.noteEditor.fontItalic():
            self.noteEditor.setFontItalic(False)
            self.italicAction.setChecked(False)
        else:
            self.noteEditor.setFontItalic(True)
            self.italicAction.setChecked(True)
    def underlineText(self):
        if self.noteEditor.fontUnderline():
            self.noteEditor.setFontUnderline(False)
            self.underlineAction.setChecked(False)
        else:
            self.noteEditor.setFontUnderline(True)
            self.underlineAction.setChecked(True)
    def justifyText(self):
        for tmpjustify in [self.justifyleftAction, self.justifycenterAction, self.justifyrightAction, self.justifyfillAction]:
            tmpjustify.setChecked(False)
        self.sender().setChecked(True)
        if self.sender() is self.justifyleftAction:
            self.noteEditor.setAlignment(Qt.AlignLeft)
        elif self.sender() is self.justifycenterAction:
            self.noteEditor.setAlignment(Qt.AlignHCenter)
        elif self.sender() is self.justifyrightAction:
            self.noteEditor.setAlignment(Qt.AlignRight)
        elif self.sender() is self.justifyfillAction:
            self.noteEditor.setAlignment(Qt.AlignJustify)
        else:
            self.common.displayError("Justify Text Error", "3.0 Text Justification failed.  Try again and if the error continues file a bug report.", "critical")

    def superscriptText(self):
        upfmt = QTextCharFormat()
        if self.noteEditor.textCursor().charFormat().verticalAlignment() == QTextCharFormat.VerticalAlignment.AlignSuperScript:
            upfmt.setVerticalAlignment(QTextCharFormat.AlignNormal)
            self.noteEditor.textCursor().setCharFormat(upfmt)
            self.superscriptAction.setChecked(False)
        else:
            upfmt.setVerticalAlignment(QTextCharFormat.AlignSuperScript)
            self.noteEditor.textCursor().setCharFormat(upfmt)
            self.superscriptAction.setChecked(True)

    def orderlistText(self):
        if self.noteEditor.textCursor().currentList() == 0 or self.noteEditor.textCursor().currentList() == None:
            self.noteEditor.textCursor().createList(QTextListFormat.Style.ListDecimal)
        self.orderlistAction.setChecked(True)
    
    def unorderlistText(self):
        if self.noteEditor.textCursor().currentList() == 0 or self.noteEditor.textCursor().currentList() == None:
            self.noteEditor.textCursor().createList(QTextListFormat.Style.ListDisc)
        self.unorderlistAction.setChecked(True)

    def updateButtons(self):
        if self.noteEditor.fontWeight() == QFont.Bold:
            self.boldAction.setChecked(True)
        elif self.noteEditor.fontWeight() == QFont.Normal:
            self.boldAction.setChecked(False)
        if self.noteEditor.fontItalic():
            self.italicAction.setChecked(True)
        else:
            self.italicAction.setChecked(False)
        if self.noteEditor.fontUnderline():
            self.underlineAction.setChecked(True)
        else:
            self.underlineAction.setChecked(False)

        if self.noteEditor.textCursor().currentList() == 0 or self.noteEditor.textCursor().currentList() == None:
            self.unorderlistAction.setChecked(False)
        else:
            self.orderlistAction.setChecked(True)
        for tmpjust in [self.justifyleftAction, self.justifycenterAction, self.justifyrightAction, self.justifyfillAction]:
            tmpjust.setChecked(False)
        if self.noteEditor.alignment() == Qt.AlignLeft:
            self.justifyleftAction.setChecked(True)
        elif self.noteEditor.alignment() == Qt.AlignHCenter:
            self.justifycenterAction.setChecked(True)
        elif self.noteEditor.alignment() == Qt.AlignRight:
            self.justifyrightAction.setChecked(True)
        elif self.noteEditor.alignment() == Qt.AlignJustify:
            self.justifyfillAction.setChecked(True)

    def addNoteSql(self):
        self.data.sql(self.data.inserNote, [self.noteEditor.toHtml(), self.noteEditor.toPlainText(), self.parent.currentcaseid], 0)

    def delNoteSql(self):
        self.data.sql(self.data.deleteNote, [self.parent.currentnoteid], 0)

    def updateNoteSql(self):
        self.data.sql(self.data.updateNoteContent, [self.noteEditor.toHtml(), self.noteEditor.toPlainText(), self.parent.currentnoteid], 0)
    
    def updateNoteListSql(self):
        self.noteList.clear()
        self.noteList.addItems(self.data.sql(self.data.updateNoteList, [self.parent.currentcaseid], 1))

    def populateNoteContentSql(self):
        currentnotedata = self.data.sql(self.data.getNoteValuesFromNoteList, [self.noteList.currentItem().text(), self.parent.currentcaseid], 1)
        if currentnotedata is not None:
            self.noteEditor.setHtml(currentnotedata[0])
            self.parent.currentnoteid = currentnotedata[1]

    def addNote(self):
        self.addNoteSql()
        self.updateNoteListSql() # update notelist with existing notes
        self.noteEditor.setHtml("") # clears text,undo and redo now that it is added to the note list.
    
    def delNote(self):
        self.chkMessage = QMessageBox.warning(self, "Delete Note", "Are you sure you want to delete the note?\n This action cannot be undone.", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if self.chkMessage is QMessageBox.StandardButton.Yes:
            self.delNoteSql()
            self.updateNoteListSql() # update notelist with removed note
            self.noteEditor.setHtml("") # clears text, undo and redo now that it is deleted from note list

    def updateNote(self):
        self.updateNoteSql() # update selected note's content
        self.updateNoteListSql()
        self.noteEditor.setHtml("")
        # upon completion of updating selected note's content, i'll probably maintain the selection in the note list..

    def showContent(self):
        if self.noteList.count() > 0 or self.noteList.count() is not None:
            self.populateNoteContentSql()
